package com.ly.quartz.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.*;
import com.ly.heart.domain.dto.KingFinanceReceiptDto;
import com.ly.heart.domain.dto.KingFinanceTransferReceiptDto;
import com.ly.heart.service.IKingBaseBankService;
import com.ly.heart.service.IKingFinanceReceiptService;
import com.ly.heart.service.IKingFinanceTransferReceiptDetailService;
import com.ly.heart.service.IKingFinanceTransferReceiptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Wuzh
 * @Description: 银行转账单定时任务，每天扫描一次，查询是否有到期的转账单；
 * 1）如果存在到期转账单，则生成一张银行转账单（进出账户调换），和一张收款单
 * 2）如果没有到期转账单，则不处理
 * @Date Created in 21:01 2024-09-10
 * @return
 */
@Component
@Slf4j
public class KingFinanceTransferReceiptTask {

    @Resource
    private IKingFinanceTransferReceiptService iKingFinanceTransferReceiptService;
    @Resource
    private IKingFinanceTransferReceiptDetailService iKingFinanceTransferReceiptDetailService;
    @Resource
    private IKingFinanceReceiptService iKingFinanceReceiptService;
    @Resource
    private IKingBaseBankService iKingBaseBankService;

    /**
     * 扫描转账单
     */
    public void scanTransferReceipt () {
        log.info ( "启动定时任务，扫描银行转账单" );
        List<KingFinanceTransferReceiptEntity> list = iKingFinanceTransferReceiptService.list ( new LambdaQueryWrapper<KingFinanceTransferReceiptEntity> ().eq ( KingFinanceTransferReceiptEntity :: getDueDate, LocalDate.now () ) );
        log.info ( "[{} 的 {}，一共 {} 条]", list, list.size () );
        if ( ! CollectionUtils.isEmpty ( list ) ) {
            list.forEach ( transfer -> {
                //获取明细行数据
                KingFinanceTransferReceiptDetailEntity transferReceiptDetailEntity = new KingFinanceTransferReceiptDetailEntity ();
                transferReceiptDetailEntity.setTransferReceiptId ( transfer.getId () );
                List<KingFinanceTransferReceiptDetailEntity> transferReceiptDetailEntities = iKingFinanceTransferReceiptDetailService.selectKingFinanceTransferReceiptDetailEntityList ( transferReceiptDetailEntity );
                KingFinanceTransferReceiptDto kingFinanceTransferReceiptDto = new KingFinanceTransferReceiptDto ();
                //1.组装新的银行转账单主表对象
                KingFinanceTransferReceiptEntity transferReceiptEntity = parseTransferReceiptEntity ( transfer );
                //2.组装新的银行转账单明细行对象
                List<KingFinanceTransferReceiptDetailEntity> newList = parseTransferReceiptDetail ( transferReceiptDetailEntities );
                kingFinanceTransferReceiptDto.setKingFinanceTransferReceiptEntity ( transferReceiptEntity );
                kingFinanceTransferReceiptDto.setKingFinanceTransferReceiptDetailEntities ( newList );
                iKingFinanceTransferReceiptService.draft ( kingFinanceTransferReceiptDto );

                KingFinanceReceiptDto dto = new KingFinanceReceiptDto ();
                //3.组装新的收款单
                KingFinanceReceiptEntity receiptEntity = parseReceipt ( transfer, transferReceiptDetailEntities );
                //4.组装新的收款单明细行
                List<KingFinanceReceiptDetailEntity> receiptDetailEntities = parseReceiptDetail ( transferReceiptDetailEntities );
                dto.setKingFinanceReceiptEntity ( receiptEntity );
                dto.setKingFinanceReceiptDetailEntities ( receiptDetailEntities );
                iKingFinanceReceiptService.draft ( dto );
            } );
        }
    }

    /**
     * 组装银行转账单主体对象
     * @param transfer
     * @return
     */
    private KingFinanceTransferReceiptEntity parseTransferReceiptEntity (KingFinanceTransferReceiptEntity transfer) {
        KingFinanceTransferReceiptEntity transferReceiptEntity = new KingFinanceTransferReceiptEntity ();
        BeanUtils.copyProperties ( transfer, transferReceiptEntity, new String[]{"instanceId", "isSend", "isUsed"} );
        transferReceiptEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        transferReceiptEntity.setParentId ( transfer.getId () ); //父Id
        return transferReceiptEntity;
    }


    /**
     * 解析银行转账单明细行
     * @param transferReceiptDetailEntities
     * @return
     */
    private List<KingFinanceTransferReceiptDetailEntity> parseTransferReceiptDetail (List<KingFinanceTransferReceiptDetailEntity> transferReceiptDetailEntities) {
        List<KingFinanceTransferReceiptDetailEntity> list = new ArrayList<> ();
        log.info ( "解析银行转账单明细行数据。" );
        for ( KingFinanceTransferReceiptDetailEntity transferReceiptDetail : transferReceiptDetailEntities ) {
            String inBankCode = transferReceiptDetail.getInBankCode (); //转入银行
            String inBankNo = transferReceiptDetail.getInBankNo (); //转入银行账户
            String outBankCode = transferReceiptDetail.getOutBankCode ();//转出银行
            String outBankNo = transferReceiptDetail.getOutBankNo ();//转出银行账户
            //调换
            transferReceiptDetail.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
            transferReceiptDetail.setInBankCode ( outBankCode );
            transferReceiptDetail.setInBankNo ( outBankNo );
            transferReceiptDetail.setOutBankCode ( inBankCode );
            transferReceiptDetail.setOutBankNo ( inBankNo );
            transferReceiptDetail.setAbstractDesc ( "到期" );
            list.add ( transferReceiptDetail );
        }
        return list;
    }


    /**
     * 组装新的收款单，收款单【单据类型：其他业务收款单；往来单位银行】
     * @param transfer
     */
    private KingFinanceReceiptEntity parseReceipt (KingFinanceTransferReceiptEntity transfer, List<KingFinanceTransferReceiptDetailEntity> transferReceiptDetailEntities) {
        KingFinanceReceiptEntity receiptEntity = new KingFinanceReceiptEntity ();
        receiptEntity.setSourceDocType ( KingConstUtil.RECEIPT_TYPE_PAY_BILL );
        receiptEntity.setDocTypeCode ( KingConstUtil.RECEIPT_OTHER_RECEIPT );
        receiptEntity.setBusinessTime ( DateUtils.getNowDate () );
        receiptEntity.setTransactionCompanyType ( "BD_BANK" ); //往来单位类型
        receiptEntity.setPayDeptType ( "BD_BANK" );
        KingFinanceTransferReceiptDetailEntity detailEntity = transferReceiptDetailEntities.get ( 0 );
        if ( detailEntity != null ) {
            KingBaseBankEntity one = iKingBaseBankService.getOne ( new LambdaQueryWrapper<KingBaseBankEntity> ().eq ( KingBaseBankEntity :: getCode, detailEntity.getOutBankCode () ) );
            receiptEntity.setTransactionCompanyId ( one.getId () );//往来单位走银行转账单的银行
            receiptEntity.setPayDeptId ( one.getId ()); //付款单位
            receiptEntity.setKingBaseCurrencyCode ( detailEntity.getKingBaseCurrencyCode () );//币别走银行转账单的币别
        }
        receiptEntity.setCopeMoney ( transfer.getTransferInAmount () );//应收金额拿银行转账单的转入金额
        receiptEntity.setActualMoney ( transfer.getTransferInAmount () );//实收金额拿银行转账单的转入金额
        receiptEntity.setSettlementCurrencyCode ( "PRE001" );//结算币别走银行转账单的币别
        receiptEntity.setCreateBy ( transfer.getCreateBy () );
        return receiptEntity;
    }

    /**
     * 解析生成收款单的明细行数据
     * @param transferReceiptDetailEntities
     * @return
     */
    private List<KingFinanceReceiptDetailEntity> parseReceiptDetail (List<KingFinanceTransferReceiptDetailEntity> transferReceiptDetailEntities) {
        List<KingFinanceReceiptDetailEntity> receiptDetailEntities = new ArrayList<> ();
        transferReceiptDetailEntities.forEach ( detail -> {
            KingFinanceReceiptDetailEntity receiptDetailEntity = new KingFinanceReceiptDetailEntity ();
            receiptDetailEntity.setKingSettlementTypeCode ( KingConstUtil.SETT_TYPE_DH ); //结算方式电汇
            receiptDetailEntity.setReceiptPurposeCode ( KingConstUtil.PURPOSE_INTEREST ); //收款用途，固定利息收入
            receiptDetailEntity.setBankNumber ( detail.getInBankNo () );//我方银行账号拿银行转账单的转入银行
            receiptDetailEntity.setActualMoney ( detail.getTransferInAmount () ); //实收金额
            receiptDetailEntity.setCopeMoney ( detail.getTransferInAmount () );//应收金额
            receiptDetailEntity.setReceiptMoney ( detail.getTransferInAmount () );//应收金额
            receiptDetailEntity.setCreateBy ( detail.getCreateBy () );
            receiptDetailEntities.add ( receiptDetailEntity );
        } );
        return receiptDetailEntities;
    }

}
